package com.bafa.dbcache;

import java.io.*;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.TreeSet;

import javax.xml.bind.*;

import com.bafa.jdbc.DBAccess;
import com.bafa.jdbc.QueryObject;
import com.bafa.middle.betwixt.Utils;
import com.bafa.objects.season.Season;
import com.bafa.objects.team.Team;
import com.bafa.services.RetrieveServices;
import com.bafa.services.SeasonServices;
import com.bafa.util.comparators.SeasonComparator;
import com.bafa.util.comparators.TopScorerComparator;

public class GrabSeasons {

	private static LinkedHashMap<Integer,Season> seasons = new LinkedHashMap();
	private static LinkedHashMap cupSeasons = new LinkedHashMap();
	private static int currentSeasonId;
	static void grabLeagueSeasons(DBAccess db) throws Exception{
		//*
		ResultSet teamsResult = db.retrieveSeasons();
		seasons = new LinkedHashMap();
		while(teamsResult.next()){
			 try{
		           
				 	
					Season season = (Season)Utils.readBetwixt(new String(teamsResult.getBytes("season")),"season",Season.class);
		            if(season.isSwitchedOn()&&season.getId()>currentSeasonId)
		            	currentSeasonId=season.getId();
		           seasons.put(season.getId(), season);
			 }catch(Exception ioe){
		            java.util.logging.Logger.global.log(java.util.logging.Level.SEVERE,
		ioe.getMessage());
		        }
			
		}//*/
		
		/*
		ObjectFactory factory = new ObjectFactory();
		QueryObject seasonsQuery = new QueryObject("season");
		seasonsQuery.addOrderBy("year",true);
		seasonsQuery.addOrderBy("id",true);
		
		
		ResultSet seasonsResults = db.query(seasonsQuery);
		int i = 0;
		while(seasonsResults.next()){
			Season season = factory.createSeason();
			season.setID(seasonsResults.getInt("id"));
			season.setSeason(seasonsResults.getString("season"));
			season.setYear(seasonsResults.getInt("year"));
			season.setLeague((seasonsResults.getString("cupleague").equalsIgnoreCase("league")));
			
			season.setSwitchedOn((seasonsResults.getInt("switchon")==1));
			if(season.isSwitchedOn()){
				if(season.getID()>currentSeasonId)
					currentSeasonId = season.getID();
			}
			
				grabIsSeasonComplete(db,season);
				GrabDivision.grabDivision(db,season);
				if(!season.isLeague()){
					grabCupRounds(db,season);
					grabPlateRounds(db,season);
				}
			db.storeSeason(season);
			seasons.put(season.getID(),season);
			i++;
		}
		//*/
		
		
	}
	/*
	
	static void grabCupSeasons(DBAccess db) throws Exception{
		QueryObject seasonsQuery = new QueryObject("season");
		seasonsQuery.addWhereAndField("cupleague","'cup'");
		seasonsQuery.addOrderBy("year",true);
		seasonsQuery.addOrderBy("id",true);
		
		
		ResultSet seasonsResults = db.query(seasonsQuery);
		int i=0;
		while(seasonsResults.next()){
			Season season = new Season(seasonsResults.getInt("id"),seasonsResults.getString("season"),seasonsResults.getInt("year"),seasonsResults.getString("cupleague"),seasonsResults.getInt("switchon"));
			if(season.isSwitchedOn()){
				if(season.getID()>currentSeasonId)
					currentSeasonId = season.getID();
			}
			
				grabIsSeasonComplete(db,season);
				GrabDivision.grabDivision(db,season);
				grabCupRounds(db,season);
				grabPlateRounds(db,season);
		
			
			cupSeasons.put(season.getID(),season);
			i++;
		}
		
		
	
	}*/
	/*
	public static Season grabSeason(DBAccess db,int seasonId)throws Exception{
		if(db==null)db = new DBAccess();
		ObjectFactory factory = new ObjectFactory();
		QueryObject seasonsQuery = new QueryObject("season");
		seasonsQuery.addWhereAndField("id",""+seasonId);
		com.bafa.objects.schema.Season season = null;
		ResultSet seasonsResults = db.query(seasonsQuery);
		while(seasonsResults.next()){
			season = factory.createSeason();
			season.setSeason(seasonsResults.getString("season"));
			season.setID(seasonsResults.getInt("id"));
			season.setYear(seasonsResults.getInt("year"));
			season.setLeague((seasonsResults.getString("cupleague").equalsIgnoreCase("league")));
			season.setSwitchedOn(seasonsResults.getInt("switchon")==1);
			if(season.isSwitchedOn()&&season.getID()>currentSeasonId)
                            currentSeasonId=season.getID();
			grabIsSeasonComplete(db,season);
			GrabDivision.grabDivision(db,season);
			if(!season.isLeague()){
				//grabCupRounds(db,season);
				//grabPlateRounds(db,season);
			}
			seasons.put(season.getID(),season);
		}
		
		return season;
	}
	private static void grabIsSeasonComplete(DBAccess db, Season season)throws Exception{
		QueryObject seasonCompletedQuery = new QueryObject("matches");
		seasonCompletedQuery.addWhereAndField("SeasonId",""+season.getID());
		seasonCompletedQuery.addWhereAndField("Played","1");
		
		ResultSet seasonCompletedResults = db.count(seasonCompletedQuery);
		
		QueryObject seasonTotalQuery = new QueryObject("matches");
		seasonTotalQuery.addWhereAndField("SeasonId",""+season.getID());
		
		ResultSet seasonTotalResults = db.count(seasonTotalQuery);
		
		while(seasonCompletedResults.next()&&seasonTotalResults.next()){
			if(seasonCompletedResults.getInt(1)==seasonTotalResults.getInt(1))
				season.setCompleted(true);
		}
	}
	*/
	public static Season[] getLeagueSeasons(){
		
		return (Season[])seasons.values().toArray(new Season[seasons.size()]);
	}
	
	public static Season[] getCupSeasons(){
		return (Season[])cupSeasons.values().toArray(new Season[seasons.size()]);
	}
	
	public static Season getSeason(int id){
		
			return (Season)seasons.get(id);
		
		
	}
	
	public static Season getCurrentSeason(){
		if(seasons.containsKey(currentSeasonId)){
			return (Season)seasons.get(currentSeasonId);
		}else{
			return (Season)cupSeasons.get(currentSeasonId);
		}
	}
	/*
	public static void grabCupRounds(DBAccess db, Season season)throws Exception{
		grabRounds(db,season,true);
	}
	*/
        /*
	public static void grabPlateRounds(DBAccess db, Season season)throws Exception{
		grabRounds(db,season,false);
	}
        */
	/*
	private static void grabRounds(DBAccess db, Season season, boolean cup)throws Exception{
		ObjectFactory factory = new ObjectFactory();
		// get all cup rounds for season	
		QueryObject queryRounds = new QueryObject("rounds");
		queryRounds.addWhereAndField("SeasonId",""+season.getID());
		if(cup)queryRounds.addWhereAndField("cup","1");
		else queryRounds.addWhereAndField("cup","0");
		queryRounds.addOrderBy("previous",false);
		
		
		Round round = null;
		try{
			ResultSet resultRounds = db.query(queryRounds);
			
			// BEGIN GET FIRST ROUND
			if(resultRounds.next()){
				// set up the round
				round = factory.createRound(); 
				round.setName(resultRounds.getString("Name"));
				round.setCup(resultRounds.getInt("Cup")>0);
				round.setID(resultRounds.getInt("ID"));
				round.setPreviousRound(resultRounds.getInt("Previous"));
				round.setConfirmed(resultRounds.getInt("Confirmed")>0);
				QueryObject queryRoundFormat = new QueryObject("roundsformat");
				queryRoundFormat.addWhereAndField("roundId",""+round.getID());
				
				ResultSet formatResult = db.query(queryRoundFormat);
				
				// now get all the matches for that round
				while(formatResult.next()){
					int groupA = formatResult.getInt("A");
					int groupB = formatResult.getInt("B");
					int posA = formatResult.getInt("posA");
					int posB = formatResult.getInt("posB");
					int bye = formatResult.getInt("bye");
					// are the respective groups complete?
					boolean groupAComplete = GrabDivision.isDivisionComplete(db,season.getID(),groupA);
					boolean groupBComplete = GrabDivision.isDivisionComplete(db,season.getID(),groupB);
					
					
					
					// now reset team names in match
					Match match = RetrieveCache.getMatch(formatResult.getInt("matchid"));
					if(groupAComplete){
						match.setHomeTeamName(GrabDivision.grabTeamInPos(season.getID(),db,groupA,posA));
						SeasonServices.confirmTeamForRound(match.getID(), season.getID(), GrabDivision.grabTeamIdInPos(season.getID(),db,groupA,posA), 0,false);
					}
					else{
						if(posA==1){
							match.setHomeTeamName("Winner Group "+groupA);
						}else if(posA==2){
							match.setHomeTeamName("Runner-up Group "+groupA);
						}else{
							match.setHomeTeamName("Position "+posA+" in Group "+groupA);
						}
					}
					if(bye>0){
						match.setAwayTeamName("BYE");
					}else if(groupBComplete){
						match.setAwayTeamName(GrabDivision.grabTeamInPos(season.getID(),db,groupB,posB));
						SeasonServices.confirmTeamForRound(match.getID(), season.getID(), 0, GrabDivision.grabTeamIdInPos(season.getID(),db,groupB,posB),false);
					}
					else{
						if(posB==1){
							match.setAwayTeamName("Winner Group "+groupB);
						}else if(posB==2){
							match.setAwayTeamName("Runner-up Group "+groupB);
						}else{
							match.setAwayTeamName("Position "+posB+" in Group "+groupB);
						}
					}
					
					// if both groups are done then confirm the round
					if(groupAComplete&&groupBComplete){
						SeasonServices.confirmRound(match.getID(),season.getID(),GrabDivision.grabTeamIdInPos(season.getID(),db,groupA,posA),GrabDivision.grabTeamIdInPos(season.getID(),db,groupB,posB),false);
					}
					round.getMatches().add(match.getID());
					db.updateMatch(match);
				}
				
				if(round.isCup()){
					season.getCupRound().add(round);
				}else{
					season.getPlateRound().add(round);
				}
				
			}
			// END GET FIRST ROUND
			
			//BEGIN GET ALL OTHER ROUNDS
			while(resultRounds.next()){
				round = factory.createRound(); 
				round.setName(resultRounds.getString("Name"));
				round.setCup(resultRounds.getInt("Cup")>0);
				round.setID(resultRounds.getInt("ID"));
				round.setPreviousRound(resultRounds.getInt("Previous"));
				round.setConfirmed(resultRounds.getInt("Confirmed")>0);
				QueryObject queryRoundFormat = new QueryObject("roundsformat");
				queryRoundFormat.addWhereAndField("roundId",""+round.getID());
				
				ResultSet formatResult = db.query(queryRoundFormat);
				
				// now get all the matches for that round
				while(formatResult.next()){
					int groupA = formatResult.getInt("A");
					int groupB = formatResult.getInt("B");
					int bye = formatResult.getInt("bye");
					// are the respective groups complete?
					boolean groupAComplete = RetrieveCache.getMatch(groupA).isPlayed();
					boolean groupBComplete = RetrieveCache.getMatch(groupB).isPlayed();
						
					// now reset team names in match
					Match match = RetrieveCache.getMatch(formatResult.getInt("matchid"));
					Match matchA = RetrieveCache.getMatch(groupA);
					if(groupAComplete){
						
						int team = 0;
						if(matchA.getHomeGoals()>matchA.getAwayGoals())
							team = matchA.getHomeTeam();
						else if(matchA.getHomeGoals()<matchA.getAwayGoals())
							team = matchA.getAwayTeam();
						match.setHomeTeam(team);
						SeasonServices.confirmTeamForRound(match.getID(), season.getID(), team, 0,false);
					}
					else{
						
						match.setHomeTeamName(matchA.getHomeTeamName()+"/"+matchA.getAwayTeamName());
					}
					Match matchB = RetrieveCache.getMatch(groupB);
					if(bye>0){
						match.setAwayTeamName("BYE");
					}else if(groupBComplete){
						
						int team = 0;
						if(matchB.getHomeGoals()>matchB.getAwayGoals())
							team = matchB.getHomeTeam();
						else if(matchB.getHomeGoals()<matchB.getAwayGoals())
							team = matchB.getAwayTeam();
						match.setAwayTeam(team);
						SeasonServices.confirmTeamForRound(match.getID(), season.getID(), 0,team,false);
					}
					else{
						match.setAwayTeamName(matchB.getHomeTeamName()+"/"+matchB.getAwayTeamName());
					}
					
					round.getMatches().add(match.getID());
					db.updateMatch(match);
					//if both groups are done then confirm the round
					if(groupAComplete&&groupBComplete){
						SeasonServices.confirmRound(match.getID(),season.getID(),match.getHomeTeam(),match.getAwayTeam(),false);
					}
				}
				
				if(round.isCup()){
					season.getCupRound().add(round);
				}else{
					season.getPlateRound().add(round);
				}
			}
			// END GET ALL OTHER ROUNDS
			
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	*/
	public static void addSeason(Season season){
		seasons.put(season.getId(), season);
	}
	/*
	private static void grabAllTimeGoalScorers(DBAccess db,int seasonId)throws Exception{
		ObjectFactory factory = new ObjectFactory();
		QueryObject scorersQuery = new QueryObject("scorers");
		
		scorersQuery.setDistinct(true);
		scorersQuery.addSelectFields("scorername");
		scorersQuery.addWhereAndField("seasonId",seasonId+"");
		
		ResultSet scorersResult = db.query(scorersQuery);
		HashMap map = new HashMap();
		int i = 0;
		while(scorersResult.next()&&i<10){
			String name = scorersResult.getString(1);
			QueryObject scorerQuery = new QueryObject("scorers");
			scorerQuery.addWhereAndField("ScorerName","'"+name+"'");
			scorerQuery.addWhereAndField("teamId",seasonId+"");
			ResultSet scorerResult = db.query(scorerQuery);
			int goals = 0;
			while(scorerResult.next()){
				goals=goals+scorerResult.getInt("NumberOfGoals");
			}
			Scorer scorer = factory.createScorer();
			scorer.setName(name);
			scorer.setGoals(goals);
			scorer.setSeasonId(seasonId);
			scorer.setTeamId(0);
			
			i++;
		}
	}
*/
	public static int getCurrentSeasonId() {
		return currentSeasonId;
	}
	public static void setCurrentSeasonId(int currentSeasonId) {
		GrabSeasons.currentSeasonId = currentSeasonId;
	}
	public static LinkedHashMap<Integer, Season> getSeasons() {
		return seasons;
	}
	public static void setSeasons(LinkedHashMap<Integer, Season> seasons) {
		GrabSeasons.seasons = seasons;
	}
	public static void setCupSeasons(LinkedHashMap cupSeasons) {
		GrabSeasons.cupSeasons = cupSeasons;
	}
}
